package com.swang.pms.web.controller.manage;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.swang.pms.common.util.EnumToDataUtil;
import com.swang.pms.common.util.LoggerUtil;
import com.swang.pms.model.annotation.PltLog;
import com.swang.pms.model.common.Pager;
import com.swang.pms.model.dto.ManageRoleDto;
import com.swang.pms.model.dto.ManageUserDto;
import com.swang.pms.model.entity.CurrentKey;
import com.swang.pms.model.entity.ManageUser;
import com.swang.pms.model.enums.AbleStatus;
import com.swang.pms.model.enums.ManagerUserStatus;
import com.swang.pms.model.enums.UserType;
import com.swang.pms.model.vo.ResultMessage;
import com.swang.pms.service.manage.ManageRoleService;
import com.swang.pms.service.manage.ManageUserService;
import com.swang.pms.web.controller.BaseController;

/**
 * @ClassName: ManagerUserController
 * @Description: 用户管理服务控制层
 * @author 王泽
 * @date 2017年3月16日 下午9:45:51
 */
@Controller
@RequestMapping("/managerUser")
public class ManageUserController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ManageUserController.class);

    @Resource
    ManageUserService           manageUserService;

    @Resource
    ManageRoleService           manageRoleService;

    @RequestMapping(value = "/editManagerUserWin")
    public ModelAndView editManagerUser(ModelMap model, @RequestParam("type") String type, @RequestParam("id") Long id) {
        model.put("type", type);
        model.put("id", id);
        return new ModelAndView("sys/win/editManagerUser", model);
    }

    @PltLog(log = "新增或者编辑一个管理员")
    @RequestMapping(value = "/saveManagerUser")
    public @ResponseBody ResultMessage saveEditManagerUser(ManageUserDto dto, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        ManageUser admin = getSessionUser(request);
        dto.setOperator(admin.getUserName());
        try {
            if (dto.getId() != null) {
                CurrentKey currentKey = new CurrentKey();
                currentKey.setId(dto.getId());
                if (!checkParam(request, currentKey)) {
                    result.change(false, "用户无权访问!");
                    return result;
                }

            } else {
                CurrentKey currentKey = new CurrentKey();
                currentKey.setId(dto.getRandomNum());
                if (!checkParam(request, currentKey)) {
                    result.change(false, "用户无权访问!");
                    return result;
                }
            }
            this.manageUserService.saveAdmin(dto);
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "save error: {0}", e.getMessage());
            result.change(false, "保存失败,错误信息:" + e.getMessage());
        }
        return result;
    }

    @PltLog(log = "编辑一个管理员")
    @RequestMapping(value = "/editManagerUser")
    public @ResponseBody ResultMessage editManagerUser(ManageUserDto admin, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "操作成功");
        CurrentKey currentKey = new CurrentKey();
        currentKey.setId(admin.getId());
        if (!checkParam(request, currentKey)) {
            result.change(false, "用户无权访问!");
            return result;
        }
        try {
            this.manageUserService.updateManagerUserByKeySelective(admin);
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "edit error: {0}", e.getMessage());
            result.change(false, "操作失败" + e.getMessage());
        }
        return result;
    }

    @PltLog(log = "查询一个管理员的信息")
    @RequestMapping(value = "/oneAdminInfo/{id}")
    public @ResponseBody ResultMessage oneAdminInfo(@PathVariable("id") Long id) {

        ResultMessage result = new ResultMessage(true, "操作成功");
        try {
            result.setContent(this.manageUserService.selectManagerUserByKey(id));
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "findOneAdminInfo error: {0}", e.getMessage());
            result.change(false, "获取失败:" + e.getMessage());
        }
        return result;
    }

    @PltLog(log = "初始化管理员管理页面")
    @RequestMapping(value = "/page")
    public ModelAndView openPage(ModelMap model) {
        String statusComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(ManagerUserStatus.class);
        String roleTypeComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(UserType.class);
        model.addAttribute("roleTypeComboData", roleTypeComboData);
        model.addAttribute("statusComboData", statusComboData);
        model.put("hosDtoList", "");
        ManageRoleDto manageRoleDto = new ManageRoleDto();
        manageRoleDto.setStatus(AbleStatus.ENABLED.getCode());
        List<ManageRoleDto> manageRoleList = this.manageRoleService.selectsBySelf(manageRoleDto);
        model.put("roleComboData", comboData(manageRoleList, ""));
        return new ModelAndView("sys/managerUserMgr", model);
    }

    @RequestMapping(value = "/findPageGrid")
    public @ResponseBody Pager findPageGrid(Pager pager, ManageUserDto admin) {
        Pager resultPage = new Pager();
        try {
            admin.setExceptStatusType(ManagerUserStatus.DELETE.getCode());
            if (admin != null && StringUtils.isNotBlank(admin.getUserName())) {
                admin.setUserName(admin.getUserName().replaceAll("%", "\\\\%"));
            }
            if (admin != null && StringUtils.isNotBlank(admin.getRealName())) {
                admin.setRealName(admin.getRealName().replaceAll("%", "\\\\%"));
            }
            if (admin != null && StringUtils.isNotBlank(admin.getTelephone())) {
                admin.setTelephone(admin.getTelephone().replaceAll("%", "\\\\%"));
            }
            resultPage = manageUserService.findPageDataByDto(pager, admin);
        } catch (Exception e) {
            resultPage.change(false, "查询失败" + e.getMessage());
            LoggerUtil.error(LOGGER, "findPageGrid error: {0}", e.getMessage());
        }
        return resultPage;
    }

    @PltLog(log = "删除一个管理账户")
    @RequestMapping(value = "/delManagerUser")
    public @ResponseBody ResultMessage deleteManagerUser(@RequestParam("id") Long id, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "删除成功");
        CurrentKey currentKey = new CurrentKey();
        currentKey.setId(id);
        if (!checkParam(request, currentKey)) {
            result.change(false, "用户无权访问!");
            return result;
        }
        ManageUserDto managerUser = new ManageUserDto();
        try {
            managerUser.setId(id);
            managerUser.setStatus(ManagerUserStatus.DELETE.getCode());
            this.manageUserService.updateManagerUserByKeySelective(managerUser);
        } catch (Exception e) {
            result.change(false, "删除失败" + e.getMessage());
            LoggerUtil.error(LOGGER, "delManagerUser error: {0}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/getHosById")
    public @ResponseBody Pager getHosById(Pager pager, ManageUserDto managerUserDto) {
        return null;
    }

    @RequestMapping(value = "/saveUserHosRef")
    public @ResponseBody ResultMessage saveUserHosRef(ManageUserDto dto) {
        ResultMessage result = new ResultMessage(true, "成功");
        try {
            if (dto.getId() == null) {
                result.change(false, "用户信息获取失败！");
                return result;
            }
        } catch (Exception e) {
            result.change(false, "保存失败,错误信息:" + e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/gotoAuthorityWin")
    public ModelAndView gotoAuthorityWin(ModelMap model, @RequestParam("id") String id) {
        if (id == null) {
            model.put("hosCodes", null);
            return new ModelAndView("sys/alipay/authAlipayUser", model);
        }
        model.put("hosCodes", "");
        return new ModelAndView("sys/win/authorityManagerUser", model);
    }

    public static String comboData(List<ManageRoleDto> manageRoleList, String selectValue) {
        StringBuilder returnStr = new StringBuilder("([[\'").append(selectValue).append("\', \'--请选择--\'],");
        if (manageRoleList == null || manageRoleList.isEmpty()) {
            return "([[\'" + selectValue + "\', \'--请选择--\']])";
        } else {
            for (int i = 0; i < manageRoleList.size(); i++) {
                ManageRoleDto dto = manageRoleList.get(i);
                returnStr.append("[\'");
                returnStr.append(dto.getId());
                returnStr.append("\',\'");
                returnStr.append(dto.getRoleName());
                returnStr.append("\']");
                if (i != manageRoleList.size() - 1) {
                    returnStr.append(",");
                }
            }
            returnStr.append("])");
        }
        return returnStr.toString();
    }
}
